package com.v.air.app.ui;

import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.v.air.app.AppManager;
import com.v.air.app.R;
import com.v.air.app.bean.DeviceBean;
import com.v.air.app.common.UIHelper;
import com.v.air.app.interfaces.UpdateClickListener;
import com.v.air.app.tools.PreferencesTool;
import com.v.air.app.tools.StringUtils;

public class MainActivity extends ViewActivity implements OnClickListener {
	public static void startActivity(Context context) {
		context.startActivity(new Intent(context, MainActivity.class));
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 1) {
				resetView_second();
			}
		}
	};

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		super.initView(view);
		// 注册广播
		register();
		B3Uart_thread = new B3UARTConnector(this, null);
		if (!B3Uart_thread.startDetection()) {
			// ToastUtil.showToast(this, "没有连接USB设备!", Toast.LENGTH_SHORT);
			B3Uart_thread = null;
		}

		timer = new Timer(true);
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				handler.sendEmptyMessage(1);
			}
		}, 500, 500);

		moreImageView.setOnClickListener(this);
		cityTextView.setOnClickListener(this);
		titleTextView.setOnClickListener(this);
	}

	@Override
	public void initData(Context mContext) {

	}

	public class DatePushReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intent.ACTION_TIME_TICK.equals(action)) {
				resetView_Minute();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.more:
		case R.id.city_name:
			SettingActivity.startActivity(getContext());
			break;
		case R.id.app_title:
			new ConfirmDialog(getContext(), new UpdateClickListener() {

				@Override
				public void onClick(boolean flag, String name) {
					if (flag) {
						PreferencesTool.putString(getContext(), "APP_TITLE",
								name);
						titleTextView.setText(name);
					}
				}
			}).show();
			break;
		default:
			break;
		}
	}

	/*********** USB broadcast receiver *******************************************/
	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
				// ToastUtil.showToast(context, "USB插入", Toast.LENGTH_SHORT);
				B3Uart_thread = new B3UARTConnector(MainActivity.this, null);
				B3Uart_thread.startDetection();

			}
			if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
				DeviceBean.clear(getContext());
				// ToastUtil.showToast(context, "USB拔出", Toast.LENGTH_SHORT);
				// if (B3Uart_thread != null) {
				// B3Uart_thread.stopDetection();
				// B3Uart_thread = null;
				// }
			}
		}
	};

	private void register() {
		// 注册时间广播
		registerReceiver(datePushReceiver = new DatePushReceiver(),
				new IntentFilter(Intent.ACTION_TIME_TICK));
		// 注册USB广播
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		intentFilter.setPriority(500);
		this.registerReceiver(mUsbReceiver, intentFilter);
	}

	@Override
	public void destroy() {
		if (timer != null) {
			timer.cancel();
		}
		// if (B3Uart_thread != null) {
		// B3Uart_thread.stopDetection();
		// B3Uart_thread = null;
		// }
		this.unregisterReceiver(mUsbReceiver);
		this.unregisterReceiver(datePushReceiver);
		DeviceBean.clear(getContext());
		super.destroy();
	}

	@Override
	public void resume() {
		super.resume();
		String title = PreferencesTool.getString(getContext(), "APP_TITLE");
		if (StringUtils.isEmpty(title)) {
			titleTextView.setText(R.string.app_title);
		} else {
			titleTextView.setText(title);
		}
		if (myApplication.getCityBean() != null) {
			getFromNet(myApplication.getCityBean().getNumber());
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return exit();
		}
		return false;
	}

	private boolean exit() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			UIHelper.toastMessage(getApplicationContext(), R.string.exit);
			exitTime = System.currentTimeMillis();
			return false;
		} else {
			AppManager.getAppManager().finishActivity();
			AppManager.getAppManager().AppExit(this.getApplicationContext());
			AppManager.getAppManager().gotoHome(this);
			return true;
		}
	}
}
